import 'dart:io';
import 'dart:convert';

import 'package:clean_app/asset/color.dart';
import 'package:clean_app/asset/modal.dart';
import 'package:clean_app/asset/storage.dart';
import 'package:clean_app/asset/textstyle.dart';
import 'package:clean_app/interface/mid_interface.dart';
import 'package:clean_app/outer/bounding_box_annotation/annotation_controller.dart';
import 'package:clean_app/outer/bounding_box_annotation/widgets/bounding_box_annotation.dart';
import 'package:clean_app/provider/task_provider.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_drawing_board/paint_contents.dart';
import 'package:path_provider/path_provider.dart';
import 'package:provider/provider.dart';
import 'package:uuid/uuid.dart';
import 'package:http/http.dart' as http;

import '../../outer/bounding_box_annotation/models/label.dart';

class ProcessImgEdit extends StatefulWidget {
  final data;

  ProcessImgEdit({super.key, required this.data});

  @override
  State<ProcessImgEdit> createState() => _ProcessImgEditState();
}

class _ProcessImgEditState extends State<ProcessImgEdit> {
  final AnnotationController annotationController = AnnotationController();

  Uint8List? imageBytes;
  double? aspectRatio;

  getByte() async {
    try {
      // 从widget.data中获取图像URL
      String imageUrl = widget.data['thumbnail_url'];

      // 下载图像
      final response = await http.get(Uri.parse(imageUrl));
      if (response.statusCode == 200) {
        imageBytes = response.bodyBytes;
        final image = await decodeImageFromList(imageBytes!);
        aspectRatio = image.width / image.height;
        print("object: ${aspectRatio}");
        _initializeAnnotations();
      }
    } catch (e) {
      print('Error loading image: $e');
    }
  }

  _initializeAnnotations() {
    if (widget.data['annotations'] != null) {
      List annotations = widget.data['annotations'];
      for (var i = 0; i < annotations.length; i++) {
        var annotation = annotations[i];
        List boundingBox = annotation['bounding_box'];
        List<Offset> offsetList = [
          Offset(boundingBox[0].toDouble(), boundingBox[1].toDouble()), // 左上
          Offset(boundingBox[2].toDouble(), boundingBox[1].toDouble()), // 右上
          Offset(boundingBox[2].toDouble(), boundingBox[3].toDouble()), // 右下
          Offset(boundingBox[0].toDouble(), boundingBox[3].toDouble()), // 左下
        ];
        annotationController.offsetLists.add(offsetList);
        annotationController.labelList.add(
          Label(
            tag: annotation['tags'][0],
            remark: annotation['remark'] ?? "",
            score: annotation['score'] ?? 80,
            offset: offsetList[0],
          ),
        );

        print(boundingBox);

        // 在DrawingController中添加矩形内容
        Map<String, dynamic> rectangleData = {
          'startPoint': {
            'dx': boundingBox[0].toDouble(),
            'dy': boundingBox[1].toDouble(),
          },
          'endPoint': {
            'dx': boundingBox[2].toDouble(),
            'dy': boundingBox[3].toDouble(),
          },
          'paint': {
            'blendMode': 3,
            'color': 4294198070, // 红色
            'filterQuality': 3,
            'invertColors': false,
            'isAntiAlias': false,
            'strokeCap': 1,
            'strokeJoin': 1,
            'strokeWidth': 8.0,
            'style': 1
          }
        };
        annotationController.drawingController.addContent(
          Rectangle.fromJson(rectangleData),
        );
      }
      print(annotationController.offsetLists);
    }
    setState(() {});
  }

  Future<File> convertToImage(Uint8List imageByte) async {
    var tempDir = await getTemporaryDirectory();
    var file =
        await File('${tempDir.path}/image_${DateTime.now().millisecond}.jpg')
            .create();
    file.writeAsBytesSync(imageByte);
    return file;
  }

  confirmUpload() async {
    LoadingDialog.show(context);
    await TaskApi().putSubmissions(widget.data['submission_id'], {
      "annotations": List.generate(
        annotationController.labelList.length,
        (idx) {
          var label = annotationController.labelList[idx];
          var offset = annotationController.offsetLists[idx];
          return {
            "type": "rectangle",
            "remark": label.remark,
            "bounding_box": [
              offset[0].dx.toInt(),
              offset[0].dy.toInt(),
              offset[2].dx.toInt(),
              offset[2].dy.toInt(),
            ],
            "tags": [label.tag],
            "score": label.score,
          };
        },
      ).toList(),
    });
    LoadingDialog.dismiss(context);
    Toast.showInCenter(text: "上传完成", context: context);
    Navigator.of(context).pop();
  }

  // 保存草稿功能
  saveDraft() async {
    try {
      // 构造草稿数据
      final draftData = {
        "client_id": Uuid().v4(),
        "timestamp": DateTime.now().millisecondsSinceEpoch,
        "image_path": "",
        "task_context": 1,
        "tags": [],
        "score": 0,
        "annotations": List.generate(
          annotationController.labelList.length,
          (idx) {
            var label = annotationController.labelList[idx];
            var offset = annotationController.offsetLists[idx];
            return {
              "type": "rectangle",
              "remark": label.remark,
              "bounding_box": [
                offset[0].dx.toInt(),
                offset[0].dy.toInt(),
                offset[2].dx.toInt(),
                offset[2].dy.toInt(),
              ],
              // "tags": [label.tag],
              // "score": label.score,
            };
          },
        ).toList(),
      };

      // 获取现有的草稿列表
      String existingDraftsStr =
          await getStorage(key: "drafts", initData: "[]");
      List<dynamic> existingDrafts = json.decode(existingDraftsStr);

      // 添加新草稿
      existingDrafts.add(draftData);

      // 保存更新后的草稿列表
      await setStorage(key: "drafts", value: json.encode(existingDrafts));

      Toast.showInCenter(text: "草稿已保存", context: context);
      Navigator.of(context).pop(); // 关闭当前页面
      Navigator.of(context).pop(); // 返回上一页
    } catch (e) {
      Toast.showInCenter(text: "保存失败: $e", context: context);
    }
  }

  getPresetTag() async {
    var _p = Provider.of<PresetTagProvider>(context, listen: false);
    _p.getData();
  }

  printData() {
    print(widget.data);
    // {submission_id: 19, thumbnail_url: https://clean-1304983633.cos.ap-guangzhou.myqcloud.com/file/20250813/20250813_022697.jpg, description: 地库 设备 排风机 正面, submission_time: 2025-08-13T15:01:23Z, annotations: [{type: rectangle, bounding_box: [105, 213, 246, 335], tags: [纸屑], score: 80}, {type: rectangle, bounding_box: [152, 85, 208, 194], tags: [脏污], score: 80}]}
  }

  @override
  void initState() {
    printData();
    getByte();
    getPresetTag();
    super.initState();
  }

  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        centerTitle: true,
        title: Text(
          "请勾画标注区域",
          style: XSTextStyle(
            context: context,
            color: os_black,
            fontSize: 16,
            fontWeight: FontWeight.bold,
          ),
        ),
        actions: [
          TextButton(
            onPressed: () {
              // setStorage(key: "drafts", value: "[]");
              confirmUpload();
            },
            child: Text(
              "完成",
              style: XSTextStyle(
                context: context,
                color: os_color,
                fontSize: 16,
                fontWeight: FontWeight.bold,
              ),
            ),
          ),
        ],
        leading: IconButton(
          onPressed: () {
            Navigator.of(context).pop();
          },
          icon: Icon(
            Icons.chevron_left,
            size: 28,
          ),
        ),
      ),
      body: ListView(
        physics: ClampingScrollPhysics(),
        children: [
          if (imageBytes != null && aspectRatio != null)
            // 使用AspectRatio保持图片比例
            Container(
              margin: EdgeInsets.only(left: 15, right: 15),
              child: AspectRatio(
                aspectRatio: aspectRatio!,
                child: ClipRRect(
                  borderRadius: BorderRadius.circular(10),
                  child: BoundingBoxAnnotation(
                    color: os_red,
                    strokeWidth: 8,
                    controller: annotationController,
                    imageBytes: imageBytes!,
                    imageWidth: (MediaQuery.of(context).size.width - 30),
                    imageHeight:
                        (MediaQuery.of(context).size.width - 30) / aspectRatio!,
                  ),
                ),
              ),
            ),
          Container(height: 20),
        ],
      ),
    );
  }
}
